<template>
  <div class="Client_content">
    <div class="overflow-auto">
      <div class="Client_body">
        <div class="top">
          <!-- 筛选时间 -->
          <div class="screen_time">
            <div class="search">
              <el-input v-model="searchWordValue" @change="changeSelectValue" size="small" placeholder="姓名/手机号"
                suffix-icon="el-icon-search"></el-input>
            </div>
            <div class="screen_datepicker screen_datepicker_action_xiaofei">
              <el-date-picker size="small" style="width: 320px;" v-model="screenDate_xiaofei" type="daterange"
                :clearable="false" range-separator="至" @change="changeSelectValue" start-placeholder="开始日期"
                end-placeholder="结束日期" value-format="yyyy-MM-dd">
              </el-date-picker>
              <i class="el-icon-date"></i>
            </div>
            <div class="screen_datepicker screen_datepicker_action_kehu">
              <el-date-picker size="small" style="width: 320px;" v-model="screenDate_kehu" type="daterange"
                :clearable="false" range-separator="至" @change="changeSelectValue" start-placeholder="开始日期"
                end-placeholder="结束日期" value-format="yyyy-MM-dd">
              </el-date-picker>
              <i class="el-icon-date"></i>
            </div>
          </div>
          <!-- END筛选时间 -->
          <div class="selectScreen">
            <div class="selectScreen_left">
              <div class="channel">
                <span class="title" style=" margin-left: 0px;">来源渠道</span>
                <el-select size="small" v-model="channelValue" placeholder="请选择" @change="changeSelectValue">
                  <el-option v-for="item in channelList" :key="item.channel_id" :label="item.name"
                    :value="item.channel_id">
                  </el-option>
                </el-select>
              </div>
              <div class="channel">
                <span class="title">客户身份</span>
                <el-select v-model="userListValue" placeholder="请选择" size="small" @change="changeSelectValue()">
                  <el-option v-for="item in userList" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </div>
              <div class="channel">
                <span class="title">标签</span>
                <el-select v-model="userTagValue" placeholder="请选择" size="small" @change="changeSelectValue()">
                  <el-option v-for="item in userTagList" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </div>
              <el-button size="small" type="text" @click="clearScreen">重置筛选</el-button>
            </div>
            <div class="selectScreen_right">
              <el-button size="small" @click="openExport">导出明细</el-button>
              <el-button size="small" type="primary" @click="AddClient">添加客户</el-button>
            </div>
          </div>
        </div>

        <div class="tableBox" :style="{ 'height': maxHeight_tableBox + 'px', }">
          <el-table ref="exportTable" :data="tableData" style="width: 100%" :maxHeight="maxHeight_table"
            :header-cell-style="{ background: '#f6f8ff', color: '#303133', fontWeight: '400' }">
            <el-table-column prop="name" label="姓名" width="180">
            </el-table-column>
            <el-table-column prop="phone" label="手机号" width="180" align="center">
            </el-table-column>
            <el-table-column prop="tag" label="客户身份" width="180" align="center">
              <template slot-scope="scope">
                <span :style="{
                  'color': scope.row.status == 1 ? '' : 'red'
                }"> {{ scope.row.status == 1 ? '普通用户' : '黑名单' }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="total_consume" label="累计消费金额" align="center">
            </el-table-column>
            <el-table-column prop="total_order_num" label="购买次数" align="center">
            </el-table-column>
            <el-table-column prop="last_time" label="上次消费时间" align="center">
            </el-table-column>
            <el-table-column prop="create_time" label="创建时间" align="center">
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="examine(scope.row)">查看</el-button>
                <el-button size="mini" type="text" @click="detail(scope.row)">详情</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <div class="pagination">
            <pagination :data="pageNation_data" @size-change="handleSizeChange" @current-change="handleCurrentChange">
            </pagination>
          </div>
        </div>
      </div>
      <el-drawer title="查单" :visible.sync="drawer" width="500px">
        <div class="drawer">
          <div class="drawer_top">
            <div class="drawer_one">
              <div>联系人</div>
              <div>手机号</div>
              <div>房型</div>
              <div>入住时间</div>
            </div>
            <!-- 订单列表 -->
            <div class="drawer_item" v-for="item in select_user_order " :key="item.id">
              <div class="drawer_two">
                <div>订单号:<span style="color:#0486fe ">{{ item.order_no }}</span> </div>
                <div> <span>渠道: {{ item.channelText }}</span> </div>
              </div>
              <div class="drawer_one drawer_border">
                <div>{{ select_user.name }}</div>
                <div>{{ select_user.phone }}</div>
                <div>{{ item.order_room[0].room_title }}</div>
                <div>{{ item.order_room[0].date }}</div>
              </div>
            </div>
          </div>
          <!-- 分页 -->
          <div class="drawer_pagination">
            <pagination :data="pageNation_data_drawer" @size-change="handleSizeChange_drawer"
              @current-change="handleCurrentChange_drawer">
            </pagination>
          </div>

        </div>
      </el-drawer>
      <el-dialog title="添加客户" :visible.sync="dialogVisible" width="500px">
        <el-form ref="add_form" label-width="60px" :label-position="labelPosition" :model="add_form">
          <el-form-item label="手机号">
            <el-input v-model="add_form.phone" size="small" style="width:200px"></el-input>
          </el-form-item>
          <el-form-item label="姓名">
            <el-input v-model="add_form.name" size="small" style="width:200px"></el-input>
          </el-form-item>
          <el-form-item label="性别">
            <el-radio-group v-model="add_form.radio">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
              <el-radio :label="0">未知</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="生日">
            <el-date-picker v-model="add_form.birthday" size="small" type="date" value-format="yyyy-MM-dd"
              style="width:200px" placeholder="选择出生年月日">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="渠道">
            <el-select v-model="add_form.channel_id" size="small" placeholder="请选择" style="width:100%">
              <el-option v-for="item in channelList" :key="item.channel_id" :label="item.name" :value="item.channel_id"
                :disabled="item.disabled">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input type="textarea" :rows="4" placeholder="请输入内容" v-model="add_form.textarea">
            </el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false" size="small">取 消</el-button>
          <el-button type="primary" @click="add_user" size="small">确 定</el-button>
        </span>
      </el-dialog>

      <ExportTable now_export="kehu" :tableHeaders="tableHeaders" :tableScreen="tableScreen"
        :drawerVisible_Table="drawerVisible_Table" @update:drawerVisible_Table="handleDrawerVisible_Table">
      </ExportTable>
    </div>
  </div>
</template>



<script>
import ExportTable from '../../components/exportTable/exportTable.vue'
import Pagination from '../../components/PaginationPage/Pagination.vue'
import { PMS_user, user_order } from '@/api/hotel_user'
export default {
  components: {
    Pagination,
    ExportTable
  },
  data() {
    return {
      // 传递分页组件的数据
      pageNation_data: {
        total: 0,
        currentPage: 1,
        currentSize: 10,
        small: false
      },
      // 导出报表组件
      drawerVisible_Table: false,
      tableHeaders: [],//表格的所有表头
      tableScreen: [],//表格筛选字段

      userTagValue: null,//选中的客户标签id
      userListValue: null,//选中的身份标签id
      searchWordValue: null,//搜索关键字
      channelValue: null,//渠道id
      screenDate_xiaofei: [],//上次消费时间（下单时间
      screenDate_kehu: [],//成为客户时间

      tableData: [],//表格数据
      userTagList: [],//选中的客户标签列表
      channelList: [],//渠道列表
      userList: [
        {
          label: '全部',
          // value: '2'
        },
        {
          label: '普通用户',
          value: '1'
        },
        {
          label: '黑名单',
          value: '0'
        }
      ],//选中的客户身份列表


      maxHeight_tableBox: window.innerHeight - 215,//表格盒子最大高度,
      maxHeight_table: window.innerHeight - 275,//表格最大高度,

      add_form: {//添加客户数据
        phone: null,
        name: null,
        radio: 1,
        textarea: null,
        birthday: null,
        channel_id: null,
      },
      dialogVisible: false,//添加客户对话框
      drawer: false,//查看抽屉
      labelPosition: 'right',
      pageNation_data_drawer: {
        total: 0,
        currentPage: 1,
        currentSize: 10,
        small: true
      },

      select_user_order: null,
      select_user: null,
    }
  },
  mounted() {
    // 监听窗口大小变化
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    // 移除窗口大小变化的监听
    window.removeEventListener('resize', this.handleResize);
  },
  created() {
    this.getUserList()
    this.getUserTag()
    this.getChannel()

  },
  methods: {
    // 重置筛选
    clearScreen() {
      this.screenDate_kehu = []
      this.screenDate_xiaofei = []
      this.searchWordValue = null
      this.userListValue = null
      this.userTagValue = null
      this.channelValue = null
      this.getUserList()
    },
    /**
     * 导出明细按钮
     */
    openExport() {
      if (this.tableData.length == 0) {
        this.$message.warning('没有可导出的数据！')
        return
      }

      const tableHeaders = Array.from(this.$refs.exportTable.$el.querySelectorAll('th')).map(header => header.innerText).filter(item => item != '');
      let userTagListName = null
      let channelListName = null

      // 渠道筛选字段
      this.channelList.forEach(item => {
        if (this.channelValue == item.channel_id) {
          channelListName = item.name
        }
      })
      // 客户标签筛选字段
      this.userTagList.forEach(item => {
        if (this.userTagValue == item.id) {
          userTagListName = item.name
        }
      })
 

      const tableScreen = [
        ['上次消费时间', this.screenDate_xiaofei.join('-') ? this.screenDate_xiaofei.join('-') : '全部', this.screenDate_xiaofei],
        ['成为客户时间', this.screenDate_kehu.join('-') ? this.screenDate_kehu.join('-') : '全部', this.screenDate_kehu],
        ['搜索关键字', this.searchWordValue ? this.searchWordValue : '全部', this.searchWordValue],
        ['来源渠道', channelListName ? channelListName : '全部', this.channelValue],
        ['客户身份', this.userListValue == 1 ? '普通用户' : this.userListValue == 0 ? '黑名单' : '全部', this.userListValue],
        ['标签', userTagListName ? userTagListName : '全部', this.userTagValue],
      ]
      console.log(tableHeaders, 'tableHeaders');
      console.log(tableScreen, 'tableScreen');
      this.tableHeaders = tableHeaders  // 报表字段
      this.tableScreen = tableScreen  // 筛选字段
      this.drawerVisible_Table = true;
    },
    // 更新父组件的抽屉状态 导出明细
    handleDrawerVisible_Table(value) {
      this.drawerVisible_Table = value;
      // console.log(value,'子传父value更新父组件的对话框状态');
    },


    // 监听窗口大小变化
    handleResize() {
      // 在这里处理窗口大小变化的逻辑
      let screenHeight = window.innerHeight;
      this.maxHeight_tableBox = screenHeight - 215
      this.maxHeight_table = screenHeight - 275
    },

    // 筛选值发生变化
    changeSelectValue() {
      this.getUserList()
    },
    // 获取客户列表
    getUserList() {
      let data = {
        hotel_id: sessionStorage.getItem('hotel_id'),
        page: this.pageNation_data.currentPage,
        page_rows: this.pageNation_data.currentSize,
        tag: this.userTagValue,
        search_word: this.searchWordValue,
        channel_id: this.channelValue,
        create_date: this.screenDate_kehu,
        order_date: this.screenDate_xiaofei,
        status: this.userListValue,//客户省份，黑名单，普通用户
        // min_order_num
        // max_order_num		
        // min_consume		
        // max_consume		
      }
      console.log(data, '客户列表数据');
      this.my_request('supplier/hotel-pms-user/list', data, 'GET').then(res => {
        let { code, data } = res.data
        console.log(res, '客户列表结果');
        if (200 == code) {
          this.tableData = data.list
          this.pageNation_data.total = data.total
        }
      })
    },
    // 客户身份列表
    getUserTag() {
      let data = {
        hotel_id: sessionStorage.getItem('hotel_id'),
        page_rows: 1000
      }
      this.my_request('supplier/hotel-pms-user/tag', data, 'GET').then(res => {
        console.log(res, '客户身份列表结果');
        let { code, data } = res.data
        if (200 == code) {
          this.userTagList = data.list
          this.userTagList.unshift({
            name: '全部',
            // channel_id: 0,
          })
        }
      })
    },
    // 渠道列表
    getChannel() {
      let data = {
        hotel_id: sessionStorage.getItem('hotel_id'),
      }
      this.my_request('supplier/hotel-pms/price/channel', data, 'GET').then(res => {
        console.log(res, '渠道列表结果');
        let { code, data } = res.data
        if (200 == code) {
          this.channelList = data
          this.channelList.unshift({
            name: '全部',
            // channel_id: 0,
          })
        }
      })
    },
    // 分页
    handleSizeChange(val) {
      // 处理每页数量改变的逻辑
      console.log(`每页 ${val} 条`);
      this.pageNation_data.currentSize = val
      this.getUserList()
    },
    handleCurrentChange(val) {
      // 处理当前页码改变的逻辑
      console.log(`当前页: ${val}`);
      this.pageNation_data.currentPage = val
      this.getUserList()
    },

    // 添加客户
    add_user() {
      let data = {
        hotel_id: sessionStorage.getItem('hotel_id'),
        phone: this.add_form.phone,
        sex: this.add_form.radio,
        birth: this.add_form.birthday,
        channel_id: this.add_form.channel_id,
        name: this.add_form.name,
      }
      // console.log(data);
      PMS_user(data, 'POST').then(res => {
        let { code, message } = res.data
        if (200 == code) {
          this.$message.success(message)
          this.dialogVisible = fasle
          this.getUserList()
        } else {
          this.$message.error(message)
        }
      })
    },
    // 添加客户对话框
    AddClient() {
      this.add_form = {
        phone: null,
        name: null,
        radio: 1,
        textarea: null,
        birthday: null,
        channel_id: null,
      }
      this.dialogVisible = true
    },




    // 分页  抽屉分页组件
    handleSizeChange_drawer(val) {
      // 处理每页数量改变的逻辑
      console.log(`每页 ${val} 条`);
      this.pageNation_data_drawer.currentSize = val
      this.getUserList()
    },
    handleCurrentChange_drawer(val) {
      // 处理当前页码改变的逻辑
      console.log(`当前页: ${val}`);
      this.pageNation_data_drawer.currentPage = val
      this.examine(this.select_user)
    },
    // 查询客户的订单
    async examine(user) {
      this.select_user = user
      let data = {
        hotel_id: sessionStorage.getItem('hotel_id'),
        user_id: user.id,
        page: this.pageNation_data_drawer.currentPage,
        page_rows: this.pageNation_data_drawer.currentSize,
        // order_no
        // order_status
      }
      await user_order(data).then(res => {
        console.log(res, '查询客户的订单结果');
        console.log(this.select_user, 'this.user');
        let { code, data } = res.data
        if (200 == code) {
          if (res.data.data.list.length > 0) {
            this.select_user_order = data.list
            this.pageNation_data_drawer.total = data.total
            this.drawer = true

            this.select_user_order.map(item => {
              item.create_time = item.create_time.substring(0, 10)
              this.channelList.forEach(element => {
                if (element.channel_id == item.channel) {
                  item.channelText = element.name
                }
              });

              return item
            })
          } else {
            this.$message({
              showClose: true,
              message: '该客户没有任何订单',
              type: 'warning'
            });
          }

        }
      })
    },

    detail(value) {
      console.log(value);
      this.$router.push({ path: '/ClientDetails', query: { id: value.id } })
    }
  }
}
</script>

<style lang="scss" scoped>
.drawer {
  padding: 30px 20px;
  border-top: 1px solid #DCDFE6;
  overflow: hidden;
  height: 100%;

  .drawer_item {
    margin-bottom: 20px;
  }

  .drawer_top {
    overflow: auto;
    height: calc(100vh - 170px);
  }

  .order_item {
    margin-bottom: 20px;
  }

  .drawer_border {
    border-bottom: 1px solid #E4E7ED;
    padding-bottom: 0px !important;

    div {
      border-left: 1px solid #E4E7ED;
      padding: 15px 0
    }

    div:last-child {
      border-right: 1px solid #E4E7ED;
    }
  }

  .drawer_one {
    display: flex;
    justify-content: space-between;
    text-align: center;
    padding-bottom: 10px;

    div:nth-child(1) {
      width: 100px;
      text-indent: 1em;
      text-align: left;
    }

    div:nth-child(2),
    div:nth-child(3) {
      width: 150px;
    }

    div:nth-child(4) {
      width: 120px;
    }
  }

  .drawer_two {
    div:nth-child(1) {
      width: 300px;
      text-indent: 1em;
    }

    span {
      margin-left: 10px;
    }

    display: flex;
    background-color: #F2F6FC;
    padding: 20px 0;
  }

}

.Client_body {
  overflow: hidden;
  width: calc(100vw - 40px);
  height: calc(100vh - 100px);
  margin: 20px;

  .top {
    .screen_time {
      display: flex;
      gap: 30px;
    }

    .selectScreen {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 15px 0 30px 0;

      .selectScreen_left {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .title {
          margin: 0 10px 0 30px;
          font-size: 14px;
        }

        .el-button {
          margin-left: 20px;
        }
      }

    }
  }

  .tableBox {
    width: 100%;
    position: relative;
    background-color: white;

    .pagination {
      width: 100%;
      padding: 15px 0;
      position: absolute;
      bottom: 0;
      right: 20px;
      background-color: white;
    }
  }
}

.el-form-item {
  margin-bottom: 15px !important;
}
</style>

<!-- 日期选择器样式 -->
<style lang="scss" scoped>
.screen_datepicker_action_xiaofei {
  ::v-deep .el-input__inner::before {
    content: '上次消费时间';
    position: absolute;
    left: 10px;
    top: 50%;
    transform: translateY(-50%);
    width: 80px;
    text-align: center;
    color: #333333;
    font-size: 13px;
  }
}

.screen_datepicker_action_kehu {
  ::v-deep .el-input__inner::before {
    content: '成为客户时间';
    position: absolute;
    left: 10px;
    top: 50%;
    transform: translateY(-50%);
    width: 80px;
    text-align: center;
    color: #333333;
    font-size: 13px;
  }
}

::v-deep .el-input__icon.el-range__icon.el-icon-date {
  display: none;
}

::v-deep .el-date-editor.el-range-editor.el-input__inner.el-date-editor--daterange.el-range-editor--small {
  padding-left: 90px;
}

.screen_datepicker {
  position: relative;
  width: 320px;
  height: 32px;
}

.screen_datepicker i {
  position: absolute;
  right: 5px;
  z-index: 7;
  color: black;
  line-height: 32px;
}
</style>